package com.example.myblog.service;

import com.example.myblog.model.TreasureItem;
import com.example.myblog.repository.TreasureItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * 百宝箱项目服务类
 */
@Service
@Transactional
public class TreasureItemService {

    @Autowired
    private TreasureItemRepository treasureItemRepository;

    @Autowired
    private OssService ossService;

    /**
     * 获取所有启用的项目（前端展示用）
     */
    public List<TreasureItem> getAllEnabledItems() {
        return treasureItemRepository.findByEnabledTrueOrderByDisplayOrderAscCreatedAtDesc();
    }

    /**
     * 获取所有项目（管理后台用）
     */
    public List<TreasureItem> getAllItems() {
        return treasureItemRepository.findAllByOrderByDisplayOrderAscCreatedAtDesc();
    }

    /**
     * 根据类型获取启用的项目
     */
    public List<TreasureItem> getEnabledItemsByType(TreasureItem.ItemType type) {
        return treasureItemRepository.findByTypeAndEnabledTrueOrderByDisplayOrderAscCreatedAtDesc(type);
    }

    /**
     * 根据类型获取所有项目（管理后台用）
     */
    public List<TreasureItem> getItemsByType(TreasureItem.ItemType type) {
        return treasureItemRepository.findByTypeOrderByDisplayOrderAscCreatedAtDesc(type);
    }

    /**
     * 根据ID获取项目
     */
    public Optional<TreasureItem> getItemById(Long id) {
        return treasureItemRepository.findById(id);
    }

    /**
     * 保存项目
     */
    public TreasureItem saveItem(TreasureItem item) {
        // 如果是新项目且没有设置显示顺序，则设置为最大值+1
        if (item.getId() == null && item.getDisplayOrder() == null) {
            Integer maxOrder = treasureItemRepository.findMaxDisplayOrder();
            item.setDisplayOrder(maxOrder + 1);
        }
        return treasureItemRepository.save(item);
    }

    /**
     * 删除项目
     */
    public void deleteItem(Long id) {
        Optional<TreasureItem> item = treasureItemRepository.findById(id);
        if (item.isPresent()) {
            TreasureItem treasureItem = item.get();
            // 如果是文件类型，删除OSS上的文件
            if (treasureItem.getType() == TreasureItem.ItemType.FILE && treasureItem.getFilePath() != null) {
                try {
                    ossService.deleteFile(treasureItem.getFilePath());
                } catch (Exception e) {
                    // 记录日志但不阻止删除操作
                    System.err.println("删除OSS文件失败: " + e.getMessage());
                }
            }
            treasureItemRepository.deleteById(id);
        }
    }

    /**
     * 添加网站收藏
     */
    public TreasureItem addWebsiteBookmark(String displayName, String url, String description, MultipartFile iconFile, Long createdBy) {
        // 检查URL是否已存在
        if (treasureItemRepository.existsByUrlAndEnabledTrue(url)) {
            throw new RuntimeException("该网站已经收藏过了");
        }

        TreasureItem item = new TreasureItem();
        item.setType(TreasureItem.ItemType.WEBSITE);
        item.setDisplayName(displayName);
        item.setUrl(url);
        item.setDescription(description);
        item.setCreatedBy(createdBy);
        
        // 处理图标
        if (iconFile != null && !iconFile.isEmpty()) {
            try {
                // 上传图标文件到OSS
                String iconPath = ossService.uploadFile(iconFile);
                item.setIcon(iconPath);
            } catch (Exception e) {
                // 如果图标上传失败，使用默认图标
                item.setIcon(getWebsiteIcon(url));
            }
        } else {
            // 如果没有上传图标，使用默认图标
            item.setIcon(getWebsiteIcon(url));
        }
        
        item.setEnabled(true);

        return saveItem(item);
    }

    /**
     * 上传文件
     */
    public TreasureItem uploadFile(MultipartFile file, String displayName, String description, Long createdBy) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        // 上传文件到OSS
        String filePath = ossService.uploadFile(file);

        // 检查文件路径是否已存在
        if (treasureItemRepository.existsByFilePathAndEnabledTrue(filePath)) {
            throw new RuntimeException("该文件已经上传过了");
        }

        TreasureItem item = new TreasureItem();
        item.setType(TreasureItem.ItemType.FILE);
        item.setDisplayName(displayName != null && !displayName.trim().isEmpty() ? displayName : file.getOriginalFilename());
        item.setFilePath(filePath);
        item.setOriginalFileName(file.getOriginalFilename());
        item.setFileSize(file.getSize());
        item.setMimeType(file.getContentType());
        item.setDescription(description);
        item.setCreatedBy(createdBy);
        item.setIcon(getFileIcon(file.getOriginalFilename()));
        item.setEnabled(true);

        return saveItem(item);
    }

    /**
     * 更新项目
     */
    public TreasureItem updateItem(Long id, String displayName, String description, String url) {
        Optional<TreasureItem> optionalItem = treasureItemRepository.findById(id);
        if (optionalItem.isEmpty()) {
            throw new RuntimeException("项目不存在");
        }

        TreasureItem item = optionalItem.get();
        item.setDisplayName(displayName);
        item.setDescription(description);
        
        // 如果是网站类型，更新URL
        if (item.getType() == TreasureItem.ItemType.WEBSITE && url != null) {
            // 检查新URL是否与其他项目冲突
            TreasureItem existingItem = treasureItemRepository.findByUrl(url);
            if (existingItem != null && !existingItem.getId().equals(id)) {
                throw new RuntimeException("该网站已经收藏过了");
            }
            item.setUrl(url);
            item.setIcon(getWebsiteIcon(url));
        }

        return saveItem(item);
    }

    /**
     * 切换项目启用状态
     */
    public TreasureItem toggleItemStatus(Long id) {
        Optional<TreasureItem> optionalItem = treasureItemRepository.findById(id);
        if (optionalItem.isEmpty()) {
            throw new RuntimeException("项目不存在");
        }

        TreasureItem item = optionalItem.get();
        item.setEnabled(!item.getEnabled());
        return saveItem(item);
    }

    /**
     * 更新项目排序
     */
    public void updateItemsOrder(List<Long> itemIds) {
        for (int i = 0; i < itemIds.size(); i++) {
            treasureItemRepository.updateDisplayOrder(itemIds.get(i), i + 1);
        }
    }

    /**
     * 搜索项目
     */
    public List<TreasureItem> searchItems(String keyword) {
        return treasureItemRepository.findByDisplayNameContainingIgnoreCaseAndEnabledTrueOrderByDisplayOrderAscCreatedAtDesc(keyword);
    }

    /**
     * 获取统计信息
     */
    public long getTotalCount() {
        return treasureItemRepository.countByEnabledTrue();
    }

    /**
     * 根据类型获取统计信息
     */
    public long getCountByType(TreasureItem.ItemType type) {
        return treasureItemRepository.countByTypeAndEnabledTrue(type);
    }

    /**
     * 根据网站URL获取图标
     */
    private String getWebsiteIcon(String url) {
        if (url == null) return "bi-globe";
        
        String domain = url.toLowerCase();
        if (domain.contains("github.com")) return "bi-github";
        if (domain.contains("stackoverflow.com")) return "bi-stack-overflow";
        if (domain.contains("youtube.com")) return "bi-youtube";
        if (domain.contains("twitter.com") || domain.contains("x.com")) return "bi-twitter-x";
        if (domain.contains("linkedin.com")) return "bi-linkedin";
        if (domain.contains("facebook.com")) return "bi-facebook";
        if (domain.contains("instagram.com")) return "bi-instagram";
        if (domain.contains("weibo.com")) return "bi-chat-dots";
        if (domain.contains("zhihu.com")) return "bi-question-circle";
        if (domain.contains("csdn.net")) return "bi-code-slash";
        if (domain.contains("juejin.cn")) return "bi-gem";
        if (domain.contains("segmentfault.com")) return "bi-bug";
        if (domain.contains("v2ex.com")) return "bi-chat-square-text";
        if (domain.contains("reddit.com")) return "bi-reddit";
        if (domain.contains("medium.com")) return "bi-medium";
        if (domain.contains("dev.to")) return "bi-code";
        if (domain.contains("npmjs.com")) return "bi-box";
        if (domain.contains("maven.org")) return "bi-archive";
        
        return "bi-globe";
    }

    /**
     * 根据文件名获取图标
     */
    private String getFileIcon(String fileName) {
        if (fileName == null) return "bi-file-earmark";
        
        String extension = "";
        int lastDot = fileName.lastIndexOf('.');
        if (lastDot > 0) {
            extension = fileName.substring(lastDot + 1).toLowerCase();
        }
        
        switch (extension) {
            case "pdf":
                return "bi-file-earmark-pdf";
            case "doc":
            case "docx":
                return "bi-file-earmark-word";
            case "xls":
            case "xlsx":
                return "bi-file-earmark-excel";
            case "ppt":
            case "pptx":
                return "bi-file-earmark-ppt";
            case "txt":
                return "bi-file-earmark-text";
            case "jpg":
            case "jpeg":
            case "png":
            case "gif":
            case "bmp":
            case "webp":
            case "svg":
                return "bi-file-earmark-image";
            case "mp4":
            case "avi":
            case "mov":
            case "wmv":
            case "flv":
                return "bi-file-earmark-play";
            case "mp3":
            case "wav":
            case "flac":
            case "aac":
                return "bi-file-earmark-music";
            case "zip":
            case "rar":
            case "7z":
            case "tar":
            case "gz":
                return "bi-file-earmark-zip";
            case "java":
            case "js":
            case "html":
            case "css":
            case "py":
            case "cpp":
            case "c":
            case "php":
            case "go":
            case "rs":
                return "bi-file-earmark-code";
            default:
                return "bi-file-earmark";
        }
    }
}